package com.ruoyi.common.core.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

@Data
public class AliyunOSSUtil {
    //节点域名
    private static final String host="oss-cn-chengdu.aliyuncs.com";

    //账号的身份ID
    private static final String accessId="LTAI5tHPmy8Kg5cq8Pkc2t7S";

    //账号的身份凭证
    private static final String accessSecret="FKaG97uBn8hSlNvdeSBXj92jhpmtnw";

    //存储空间名
    private static final String bucketName="lyz-114";

    /**
     * 上传文件
     * @param multipartFile 文件
     * @return 文件的访问地址
     */
    public static String uploadFile(MultipartFile multipartFile) {
        //创建客户端对象
        OSS ossClient = new OSSClientBuilder().build(
                "https://"+host, accessId,accessSecret);
        String suffix = StringUtils.getFilenameExtension(multipartFile.getOriginalFilename());
        String prefix = UUID.randomUUID().toString();
        String name= prefix + "." + suffix;
        InputStream file = null;
        try {
            //进行文件校验
            ImageUtil.validateImage(multipartFile);
            //获取流
            file = multipartFile.getInputStream();
            //上传
            ossClient.putObject(bucketName, name, file);
        } catch (Exception e){
            throw new RuntimeException("上传文件失败:"+e.getMessage(),e);
        } finally {
            try {
                if (file != null) {
                    file.close();
                }
            } catch (IOException e) {
                System.err.println("文件流关闭失败: " + e.getMessage());
            }
            if(ossClient != null) ossClient.shutdown();
        }
        System.out.println("上传成功");
        return "https://" + bucketName + "."+ host + "/"+name;
    }

    /**
     * 删除文件
     * @param url 文件路径
     * @return
     */
    public static boolean deleteFile(String url) {
        String objectName = extractObjectNameFromUrl(url);
        if (objectName == null || objectName.isEmpty()) {
            System.err.println("删除失败：无法从URL中提取文件名");
            return false;
        }
        OSS ossClient = new OSSClientBuilder().build(
                "https://"+host, accessId,accessSecret);
        try {
            //删除文件
            ossClient.deleteObject(bucketName, objectName);
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
        return true;
    }
    /**
     * 从完整的文件 URL 中提取出 OSS 对象名（即路径）
     * 例如：https://your-bucket.oss-cn-shenzhen.aliyuncs.com/path/to/file.jpg
     * 提取结果：path/to/file.jpg
     */
    private static String extractObjectNameFromUrl(String url) {
        try {
            URL u = new URL(url);
            return u.getPath().startsWith("/") ? u.getPath().substring(1) : u.getPath();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
    }

}
